package me.send.produce.client.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import me.send.business.base.ErrorEntity;
import me.send.business.base.Page;
import me.send.business.base.SendVariable;
import me.send.business.base.jpush.JPush;
import me.send.business.base.oss.OSSObjectSample;
import me.send.business.service.bean.CompletedBean;
import me.send.business.service.bean.OrderBrokerBean;
import me.send.business.service.bean.OrderInfoBean;
import me.send.business.service.bean.ReturnBean;
import me.send.business.service.bean.ReturnJsonBean;
import me.send.business.service.cons.MessageCons;
import me.send.business.service.cons.OrderCons;
import me.send.business.service.cons.ProgressCons;
import me.send.business.service.cons.PushStr;
import me.send.business.service.pojo.Message;
import me.send.business.service.pojo.OrderInfoV1_1_1Bean;
import me.send.business.service.pojo.OrderProgress;
import me.send.business.service.pojo.Orders;
import me.send.business.service.service.AdvertService;
import me.send.business.service.service.MessageService;
import me.send.business.service.service.OpencityService;
import me.send.business.service.service.OrderBrokerService;
import me.send.business.service.service.OrderProgressService;
import me.send.business.service.service.OrdersService;
import me.send.framework.util.HelperUtil;
import me.send.framework.util.LoggerUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.jpush.api.JPushClient;

@Controller
@RequestMapping(value = "orders")
public class OrdersController {

	@Autowired
	private OrdersService ordersService;
	@Autowired
	OrderBrokerService orderBrokerService;
	@Autowired
	MessageService messageService;
	@Autowired
	OpencityService opencityService;
	@Autowired
	OrderProgressService orderProgressService;
	
	@Autowired
	AdvertService advertService;

	// 发布 2015年6月2日11:33:14
	@RequestMapping("release/userid")
	@ResponseBody
	public ErrorEntity release_userid(Orders orders,String devicenumber,HttpServletRequest request,@RequestParam(value = "orderpics", required = false) MultipartFile[] orderpics,@RequestParam(value = "voicepath_v", required = false) MultipartFile voicepath_v)throws Exception {
		String format, originalFilename, key = "";
		LoggerUtils.warn(getClass().getName(), "addId:"+orders.getAddressId()+",toid:"+orders.getToAddressId());
		String cityname = orders.getCityname();
		int isOpen = opencityService.getCityIsOpenByName(cityname);
		if (cityname!=null) {
			if (isOpen==1) {
				if (orders.getDescption() != null
						&& !orders.getDescption().equals("")) {
				} else {
					// 接受过来的语音 2015年6月9日18:02:10
					if (voicepath_v != null) {

						originalFilename = voicepath_v.getOriginalFilename();
						format = originalFilename.substring(originalFilename
								.lastIndexOf("."));
						key = orders.getUserid() + "_voice_"
								+ System.currentTimeMillis() + format;

						String resultPath = OSSObjectSample
								.OSSPutObject(key, voicepath_v,
										SendVariable.PRODUCE_CLIENT + "/order");

						orders.setVoicepath(resultPath); // 换一下
					}
				}
				// 实例化一个list 放图片的路径使用
				List<String> picpathList = new ArrayList<String>();

				if (orderpics != null && orderpics.length > 0) {
					// 保存图片
					for (MultipartFile multipartFile : orderpics) {
						originalFilename = multipartFile.getOriginalFilename();
						format = originalFilename.substring(originalFilename
								.lastIndexOf("."));
						key = orders.getUserid() + "_pic_" + System.currentTimeMillis()
								+ "_" + HelperUtil.uuid().substring(0, 3) + format;
						String resultPath = OSSObjectSample.OSSPutObject(key,
								multipartFile, SendVariable.PRODUCE_CLIENT + "/order");
						picpathList.add(resultPath);
					}
				}
				return ordersService.release_userid(orders, devicenumber, picpathList);
			}else {
				//该城市没有开放
				return new ErrorEntity("1009", "city not open", "该城市未开放");
			}
		}else {
			//城市名为空
			return new ErrorEntity("1010", "choose city", "请选择城市");
		}
	}

	@RequestMapping(value = "list/page/userid")
	@ResponseBody
	public Map<String, Object> list_page_userid(int userid, Page page,
			String devicenumber) {
		return ordersService.list_page_userid(userid, page, devicenumber);
	}

	/**
	 * 获取用户已完成列表
	 * 
	 * @param userid
	 * @param startid
	 * @param size
	 * @param devicenumber
	 * @return
	 * @author maxmin
	 * @date 2015年8月31日上午11:46:05
	 */
	@RequestMapping(value = "list/completed")
	@ResponseBody
	public ReturnJsonBean completedOrders(int userid, int startid, int size,
			String devicenumber) {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			List<CompletedBean> orders = ordersService.completedOrders(userid,
					startid, size, devicenumber);
			rb.setDatas(orders);
			rb.setCode(ReturnJsonBean.SUCCESS);
			rb.setMessage(ReturnJsonBean.SUCCESS_STR);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rb;
	}

	// 编辑 取消 订单 系统变量 user_order_time
	@RequestMapping("delete/orders/orderid")
	@ResponseBody
	public ErrorEntity delete_orders_orderid(String devicenumber, int orderid) {
		return ordersService.delete_orders_orderid(devicenumber, orderid);
	}

	/**
	 * 取消订单
	 * 
	 * @param devicenumber
	 * @param orderid
	 * @return
	 */
	@RequestMapping("delete")
	@ResponseBody
	public ReturnBean deleteOrder(String devicenumber, int orderid, int userid) {
		ReturnBean rb = new ReturnBean();
		int result = ordersService.deleteOrder(orderid, userid);
		if (result > 0) {
			rb.setCode(ReturnBean.SUCCESS);
			rb.setMessage(ReturnBean.SUCCESS_STR);
		}
		return rb;
	}
	/**
	 * 申请取消订单
	 * 
	 * @param devicenumber
	 * @param orderid
	 * @return
	 */
	@RequestMapping("needCancel")
	@ResponseBody
	public ReturnBean needCancelOrder(String devicenumber, int orderid, int userid) {
		ReturnBean rb = new ReturnBean();
		int result = ordersService.needCancelOrder(orderid, userid);
		if(result==-1){
			rb.setCode(-1);
			rb.setMessage("不能重复申请取消订单");
			return rb;
		}
		if(result==-2){
			rb.setCode(-2);
			rb.setMessage("当前订单状态不能申请取消订单");
			return rb;
		}
		
		if (result > 0) {
			// 发送通知给经纪人
						String isvAccount = ordersService
								.getBrokerIsvAccountByOrderId(orderid);
						JPushClient client = JPush.getBrokerJPushClient();
						JPush.pushWithAlias(client, OrderCons.NEED_CANCEL, isvAccount);
						// 保存消息记录
						int brokerId = ordersService.getBrokerIdByOrderId(orderid);
						Message message = new Message(OrderCons.NEED_CANCEL, brokerId,
								MessageCons.USER_TYPE_BROKER,
								MessageCons.MESSAGE_TYPE_ORDER);
						message.setCreatetime(HelperUtil.getCurrentDate());
						message.setUpdatetime(HelperUtil.getCurrentDate());
						messageService.saveMessage(message);
			rb.setCode(ReturnBean.SUCCESS);
			rb.setMessage(ReturnBean.SUCCESS_STR);
		}
		return rb;
	}

	// 查看订单 2015年6月4日14:46:38
	@RequestMapping("one/orderid")
	@ResponseBody
	public Map<String, Object> one_orderid(String devicenumber, int orderid) {
		return ordersService.one_orderid(devicenumber, orderid);
	}

	/**
	 * 获取订单详情
	 *
	 * @param devicenumber
	 * @param orderid
	 * @return
	 */
	@RequestMapping(value = "info")
	@ResponseBody
	public ReturnJsonBean getOrderInfo(String devicenumber, int orderid) {
		ReturnJsonBean rb = new ReturnJsonBean();
		OrderInfoBean orderInfo = ordersService.getOrderInfo(orderid);
		if (orderInfo != null) {
			String picpath = orderInfo.getPicpath();
			if (picpath != null && !"".equals(picpath)) {
				String[] picpaths = picpath.split(",");
				orderInfo.setPicpaths(picpaths);
				orderInfo.setPicpath("");
			}
			rb.setCode(ReturnBean.SUCCESS);
			rb.setMessage(ReturnBean.SUCCESS_STR);
			rb.setDatas(orderInfo);
		} else {
			rb.setMessage("没有这个订单");
		}
		return rb;
	}
	
	/**
	 * 获取订单详情(新、增加折扣金额和红包金额)
	 *
	 * @param devicenumber
	 * @param orderid
	 * @return
	 */
	@RequestMapping(value = "detail")
	@ResponseBody
	public ReturnJsonBean getOrderInfoV1(String devicenumber, int orderid) {
		ReturnJsonBean rb = new ReturnJsonBean();
		OrderInfoV1_1_1Bean orderInfo = ordersService.getOrderInfoForV1_1_1(orderid);
		if (orderInfo != null) {
			String picpath = orderInfo.getPicpath();
			if (picpath != null && !"".equals(picpath)) {
				String[] picpaths = picpath.split(",");
				orderInfo.setPicpaths(picpaths);
				orderInfo.setPicpath("");
			}
			rb.setCode(ReturnBean.SUCCESS);
			rb.setMessage(ReturnBean.SUCCESS_STR);
			rb.setDatas(orderInfo);
		} else {
			rb.setMessage("没有这个订单");
		}
		return rb;
	}

	// 增加小费 2015年6月4日14:36:28 追加小费
	@RequestMapping("update/tip")
	@ResponseBody
	public ReturnJsonBean update_tip_orderid(int orderid, Double tip,
			String devicenumber) {
		ReturnJsonBean rb = new ReturnJsonBean();
		try {
			int result = ordersService.update_tip_orderid(orderid, tip,
					devicenumber);
			if (result > 0) {
				rb.setCode(ReturnJsonBean.SUCCESS);
				rb.setMessage(ReturnJsonBean.SUCCESS_STR);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rb;
		// return ordersService.update_tip_orderid(orderid,tip, devicenumber);
	}

	/**
	 * 增加小费
	 * 
	 * @param orders
	 * @param devicenumber
	 * @return
	 */
	@RequestMapping("addtip")
	@ResponseBody
	public ReturnBean addTip(double tip,final int orderid, String devicenumber,
			int userid) {
		ReturnBean rb = new ReturnBean();
		int addTip = ordersService.addTip(tip, orderid, userid);
		if (addTip > 0) {
			new Thread(new Runnable() {
				public void run() {
					Map<String, String> ext = ordersService.getOrderLocation(orderid);
					// 应该增加通知，通知经纪人有加小费的订单
					JPushClient client = JPush.getBrokerJPushClient();
//					JPush.pushAll(client, PushStr.ORDER_WITH_TIP_NOTICE);
					//ext.put("orderid", orderid+"");
					JPush.pushLBSMessageAllWithExTra(client, PushStr.ORDER_WITH_TIP_NOTICE, ext);
				}
			}).start();
			rb.setCode(ReturnBean.SUCCESS);
			rb.setMessage(ReturnBean.SUCCESS_STR);
		}
		return rb;
	}

	// 验证这个订单是否过期 2015年6月4日16:02:59
	@RequestMapping(value = "verification")
	@ResponseBody
	public ErrorEntity verification(String devicenumber, int orderid) {
		return ordersService.verification(devicenumber, orderid);
	}

	/**
	 * 获取经纪人已抢单的订单列表
	 * 
	 * @param devicenumber
	 * @param orderid
	 * @return
	 */
	@RequestMapping(value = "orderbrokerlist")
	@ResponseBody
	public ReturnBean orderBrokerList(String devicenumber, int orderid,Integer type) {
		ReturnBean returnBean = new ReturnBean();
		try {
			List<OrderBrokerBean> list = ordersService.orderBrokerList(devicenumber, orderid,type);
			returnBean.setDatas(list);
			returnBean.setCode(ReturnBean.SUCCESS);
			returnBean.setMessage(ReturnBean.SUCCESS_STR);
			return returnBean;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return returnBean;
	}

	/**
	 * 选择已抢单的经纪人接口
	 * 
	 * @return
	 */
	@RequestMapping(value = "/checkbroker")
	@ResponseBody
	public ReturnBean checkBroker(Long orderBrokerId, int orderid,
			String devicenumber) {
		ReturnBean returnBean = new ReturnBean();
		int result = orderBrokerService.checkBroker(orderBrokerId, orderid,
				devicenumber);

		if (result > 0) {
			// 发通知给经纪人
			final String brokerNoticeId = orderBrokerService.getBrokerNoticIdByOrderBrokerId(orderBrokerId);
			final long obid = orderBrokerId;
			final int oid = orderid;
			new Thread(new Runnable() {
				public void run() {
					JPushClient client = JPush.getBrokerJPushClient();
					JPush.pushWithAlias(client, OrderCons.CHOOSE_BROKER, brokerNoticeId);
					// 保存消息记录
					int brokerId = orderBrokerService
							.getBrokerIdByOrderBrokerId(obid);
					Message message = new Message(OrderCons.CHOOSE_BROKER, brokerId,
							MessageCons.USER_TYPE_BROKER,
							MessageCons.MESSAGE_TYPE_ORDER);
					message.setCreatetime(HelperUtil.getCurrentDate());
					message.setUpdatetime(HelperUtil.getCurrentDate());
					messageService.saveMessage(message);
					//记录进度
					OrderProgress op = new OrderProgress();
					op.setUserMsg(ProgressCons.ORDER_ACCEPTED_MSG);
					op.setContent(ProgressCons.ORDER_ACCEPTED_CONTENT);
					op.setOrderid(oid);
					op.setOrderStatus(OrderCons.ORDER_ACCEPTED);
					op.setCreatetime(HelperUtil.getCurrentDate());
					op.setUpdatetime(HelperUtil.getCurrentDate());
					orderProgressService.addOrderProgress(op);
				}
			}).start();
			returnBean.setCode(ReturnBean.SUCCESS);
			returnBean.setMessage(ReturnBean.SUCCESS_STR);
			return returnBean;
		}
		return returnBean;
	}

	/**
	 * 用户确认完成
	 * 
	 * @param orderid
	 * @return
	 */
	@RequestMapping(value = "/confirmComplet")
	@ResponseBody
	public ReturnBean confirmComplet(int orderid) {
		ReturnBean returnBean = new ReturnBean();
		int result = ordersService.confirmComplet(orderid);
		if (result > 0) {
			// 发送通知给经纪人
			String isvAccount = ordersService
					.getBrokerIsvAccountByOrderId(orderid);
			JPushClient client = JPush.getBrokerJPushClient();
			JPush.pushWithAlias(client, OrderCons.CONFROM_COMPLET, isvAccount);
			// 保存消息记录
			int brokerId = ordersService.getBrokerIdByOrderId(orderid);
			Message message = new Message(OrderCons.CONFROM_COMPLET, brokerId,
					MessageCons.USER_TYPE_BROKER,
					MessageCons.MESSAGE_TYPE_ORDER);
			message.setCreatetime(HelperUtil.getCurrentDate());
			message.setUpdatetime(HelperUtil.getCurrentDate());
			messageService.saveMessage(message);
			returnBean.setCode(ReturnBean.SUCCESS);
			returnBean.setMessage(ReturnBean.SUCCESS_STR);
		}
		return returnBean;
	}

	@RequestMapping(value="/progress")
	@ResponseBody
	public ReturnJsonBean orderProgressList(String devicenumber,int orderid){
		ReturnJsonBean returnBean = new ReturnJsonBean();
		try {
			List<OrderProgress> data = ordersService.getOrderProgressesByOrderId(orderid);
			returnBean.setCode(ReturnJsonBean.SUCCESS);
			returnBean.setMessage(ReturnJsonBean.SUCCESS_STR);
			returnBean.setDatas(data);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return returnBean;
	}
	
	@RequestMapping(value="/isdiscount")
	@ResponseBody
	public ReturnJsonBean checkIsDiscounted(String devicenumber,int userId,int advertId){
		ReturnJsonBean returnBean = new ReturnJsonBean();
		try {
			String date = HelperUtil.getCurrentDate("yyyy-MM-dd");
			int isDiscounted = advertService.checkIsDiscounted(userId, advertId,date);
			if (isDiscounted>0) {
				returnBean.setCode(ReturnJsonBean.FAIL);
				returnBean.setMessage("亲，今日优惠已使用，请明日继续关注，如有需求，请直接呼单");
			}else {
				returnBean.setCode(ReturnJsonBean.SUCCESS);
				returnBean.setMessage(ReturnJsonBean.SUCCESS_STR);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return returnBean;
	}
}
